package com.hknc.btscale;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hknc.btscale.adapter.AutoPollAdapterYCL;
import com.hknc.btscale.adapter.GoodsAdapter;
import com.hknc.btscale.adapter.TableAdapter;
import com.hknc.btscale.bean.BackToServer;
import com.hknc.btscale.bean.ChangeUser;
import com.hknc.btscale.bean.Constants;
import com.hknc.btscale.bean.GoodsBean;
import com.hknc.btscale.bean.LoginResponse;
import com.hknc.btscale.bean.NormalResponse;
import com.hknc.btscale.bean.OffLineData;
import com.hknc.btscale.bean.OrderResult;
import com.hknc.btscale.bean.PlayBean;
import com.hknc.btscale.bean.SaveGoods;
import com.hknc.btscale.bean.SaveOrderBean;
import com.hknc.btscale.bean.Test;
import com.hknc.btscale.bean.TicketBean;
import com.hknc.btscale.bean.TodayCheapBean;
import com.hknc.btscale.bean.UploadStatus;
import com.hknc.btscale.bean.VersionApkBean;
import com.hknc.btscale.broadcast.NetWorkStateReceiver;
import com.hknc.btscale.broadcast.WSDataReceiver;
import com.hknc.btscale.greendao.DaoSession;
import com.hknc.btscale.greendao.SaveGoodsDao;
import com.hknc.btscale.service.WebSocketService;
import com.hknc.btscale.utils.BTSendDataUtils;
import com.hknc.btscale.utils.CircleTransForm;
import com.hknc.btscale.utils.DataConvertUtils;
import com.hknc.btscale.utils.DownloadUtils;
import com.hknc.btscale.utils.Model;
import com.hknc.btscale.utils.NetUtils;
import com.hknc.btscale.utils.PackageUtils;
import com.hknc.btscale.utils.QRCodeUtils;
import com.hknc.btscale.utils.SPUtils;
import com.hknc.btscale.utils.SlientInstall;
import com.hknc.btscale.utils.network.ApiWrapper;
import com.hknc.btscale.utils.network.MyObserver;
import com.hknc.btscale.utils.network.RxHelper;
import com.hknc.btscale.utils.network.exception.ExceptionHandle;
import com.hknc.btscale.view.TextBold;
import com.kongzue.dialog.v3.WaitDialog;
import com.squareup.picasso.Picasso;
import com.stx.xhb.androidx.XBanner;
import com.stx.xhb.androidx.transformers.Transformer;
import com.zhuang.zbannerlibrary.ZBanner;
import com.zhuang.zbannerlibrary.ZBannerAdapter;

import org.greenrobot.greendao.query.QueryBuilder;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.ConnectCallback;
import cn.wandersnail.bluetooth.EventObserver;
import cn.wandersnail.commons.observer.Observe;
import cn.wandersnail.commons.poster.RunOn;
import cn.wandersnail.commons.poster.Tag;
import cn.wandersnail.commons.poster.ThreadMode;
import io.reactivex.disposables.Disposable;

public class YangcanliActivity extends AppCompatActivity implements EventObserver {
    private static final String TAG = "YangcanliActivity";
    private RatingBar mRatingBar;
    private TextView phonenumTv, pingleiTv, nameTv, tanweihaoTv, rateOfCheckTv, checkPcs, transactionNumTv, sumTv, martetNameTv, sumTv1;
    private RelativeLayout infoFl, bannerFl;
    private int part1, part2;
    private DaoSession mDaoSession;
    private ImageView touxiang, alipayImg, pingjia_img;
    private BluetoothDevice mBluetoothDevice;
    private byte[] mBytes = new byte[]{};
    private WSDataReceiver mWSDataReceiver;
    private String tanweihao, plu;
    private AutoScrollRecyclerView mRecyclerView;
    private BackToServer backToServer;
    private ZBanner mZBanner;
    private LinkedHashMap linkedHashMap;
    //    private Banner mBanner;
    private VideoView mVideoView;
    private Gson mGson;
    private SmartTable mSmartTable;
    private FrameLayout tableFl;
    private Column<String> column1;
    private Column<Double> column2;
    private Column<Double> column3;
    private Column<Double> column4;

    private CopyOnWriteArrayList<Test> list;
    private TableData<Test> tableData;
    private GoodsBean mGoodsBean;
    private int mSendSucess;
    private List<SaveGoods> saveGoodsList;
    private XBanner mXBanner;
    private RecyclerView tableRv;
    private LinearLayoutManager mManager = new LinearLayoutManager(this);
    private TableAdapter adapter;
    private FrameLayout tableMain;

    @Override
    protected void onStart() {
        super.onStart();
        BTManager.getInstance().registerObserver(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewData(Constants.sLoginResponse);

        QueryBuilder<SaveGoods> saveGoodsQueryBuilder
                = mDaoSession.queryBuilder(SaveGoods.class)
                .orderAsc(SaveGoodsDao.Properties.Plu);

        List<SaveGoods> list = saveGoodsQueryBuilder.list();
        saveGoodsList = list;
        if (list != null) {
            if (list.size() > 0) {
                initGoodsPlay(list, true);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mZBanner.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mWSDataReceiver != null) {
            unregisterReceiver(mWSDataReceiver);
        }

        if (mNetWorkStateReceiver != null) {
            unregisterReceiver(mNetWorkStateReceiver);
        }

        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        if (changeUserTimer != null) {
            changeUserTimer.cancel();
        }
        if (mVideoView != null) {
            mVideoView = null;
        }

        Intent intent = new Intent(YangcanliActivity.this, WebSocketService.class);
        stopService(intent);//关闭服务
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void initListener() {
        //头像点击事件监听
        touxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
        mNetWorkStateReceiver.setWifiStatus(new NetWorkStateReceiver.WifiStatus() {//上传离线交易数据
            @Override
            public void isConnect(boolean isConnect) {

            }
        });
        WebSocketService.setConnectCallBack(new WebSocketService.ConnectCallBack() {
            @Override
            public void connect(boolean isConnect) {
                if (isConnect) {
                    if (mDaoSession.loadAll(OffLineData.class).size() > 0) {
                        uploadOffLineData(mDaoSession.loadAll(OffLineData.class));
                    }
                }
            }
        });
        mWSDataReceiver.setDoSomethingCallBack(new WSDataReceiver.DoSomethingCallBack() {

            //连接ws成功后调用获取轮播商品的接口
            @Override
            public void success() {
            }

            @Override
            public void setType(int type) {

            }

            //播放规则
            @Override
            public void setPlayRules(PlayBean playBean) {
                if (playBean == null) {
                    return;
                }
                if (playBean.getData() == null) {
                    return;
                }
                initBanner(playBean);

            }

            //今日特价
            @Override
            public void setTodayCheap(TodayCheapBean bean) {
                if (bean == null) {
                    return;
                }
                if (bean.getData() == null) {
                    return;
                }
                initTodayCheap(bean);
            }

            //单条下发plu信息
            @Override
            public void setPluInfo(GoodsBean goodsBean) {
                if (goodsBean == null) {
                    return;
                }
                if (goodsBean.getData() == null) {
                    return;
                }
                Log.e(TAG, "连上了吗: " + isBTConnect);
                if (isBTConnect) {
                    plu = goodsBean.getData().get(0).getPlu();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            BTSendDataUtils.sendPluData(mBluetoothDevice, goodsBean.getData().get(0).getPlu(),
                                    Integer.parseInt(goodsBean.getData().get(0).getGoodsPrice()),
                                    goodsBean.getData().get(0).getGoodsName(),
                                    Integer.parseInt(goodsBean.getData().get(0).getMaxGoodsPrice()),
                                    goodsBean.getData().get(0).getIndexNo(), goodsBean.getData().get(0).getUnit());

                            SaveGoods saveGoods = new SaveGoods();
                            saveGoods.setGoodsImg(goodsBean.getData().get(0).getGoodsImg());
                            saveGoods.setUnit(goodsBean.getData().get(0).getUnit());
                            saveGoods.setStallId(goodsBean.getData().get(0).getStallId());
                            saveGoods.setMaxGoodsPrice(goodsBean.getData().get(0).getMaxGoodsPrice());
                            saveGoods.setMerchantId(goodsBean.getData().get(0).getMerchantId());
                            saveGoods.setGoodsId(goodsBean.getData().get(0).getGoodsId());
                            saveGoods.setGoodsPrice(goodsBean.getData().get(0).getGoodsPrice());
                            saveGoods.setPlu(goodsBean.getData().get(0).getPlu());
                            saveGoods.setStallNo(goodsBean.getData().get(0).getStallNo());
                            saveGoods.setGoodsName(goodsBean.getData().get(0).getGoodsName());
                            saveGoods.setMarketId(goodsBean.getData().get(0).getMarketId());
                            saveGoods.setIndexNo(goodsBean.getData().get(0).getIndexNo());
                            saveGoods.setIsSendSuccess(1);

                            mDaoSession.insertOrReplace(saveGoods);

                            saveGoodsList = mDaoSession.loadAll(SaveGoods.class);

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = new Message();
                            message.what = 10;
                            mHandler.sendMessage(message);
                        }
                    }).start();

                } else {
//                    mDaoSession.insertOrReplace()
                    // TODO: 2021/4/10 未连接蓝牙的情况下
                    SaveGoods saveGoods = new SaveGoods();
                    saveGoods.setGoodsImg(goodsBean.getData().get(0).getGoodsImg());
                    saveGoods.setUnit(goodsBean.getData().get(0).getUnit());
                    saveGoods.setStallId(goodsBean.getData().get(0).getStallId());
                    saveGoods.setMaxGoodsPrice(goodsBean.getData().get(0).getMaxGoodsPrice());
                    saveGoods.setMerchantId(goodsBean.getData().get(0).getMerchantId());
                    saveGoods.setGoodsId(goodsBean.getData().get(0).getGoodsId());
                    saveGoods.setGoodsPrice(goodsBean.getData().get(0).getGoodsPrice());
                    saveGoods.setPlu(goodsBean.getData().get(0).getPlu());
                    saveGoods.setStallNo(goodsBean.getData().get(0).getStallNo());
                    saveGoods.setGoodsName(goodsBean.getData().get(0).getGoodsName());
                    saveGoods.setMarketId(goodsBean.getData().get(0).getMarketId());
                    saveGoods.setIndexNo(goodsBean.getData().get(0).getIndexNo());
                    saveGoods.setIsSendSuccess(0);

                    mDaoSession.insertOrReplace(saveGoods);
                }

            }

            //小票信息
            @Override
            public void setTicketInfo(TicketBean ticketBean) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getAlipayCode(), (byte) 27);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getWeChatCode(), (byte) 26);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getAdvertisingText3(), (byte) 19);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getAdvertisingText2(), (byte) 18);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getAdvertisingText1(), (byte) 17);//广告文本1
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage8(), (byte) 11);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage7(), (byte) 10);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage6(), (byte) 9);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage5(), (byte) 8);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage4(), (byte) 7);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage3(), (byte) 6);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage2(), (byte) 5);
                        SystemClock.sleep(1000);
                        BTSendDataUtils.sendTicket(mBluetoothDevice, ticketBean.getReceiptPromptMessage1(), (byte) 4);

                        BackToServer backToServer = new BackToServer();
                        backToServer.setType(2);
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu("");
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("下发小票成功！");
                        backToServer(backToServer, 2);
                    }
                }).start();
            }

            //测试合格率
            @Override
            public void setRateOfCheck(String str) {
                rateOfCheckTv.setText(str);
                SPUtils.getInstance(getBaseContext()).putSP("rateOfCheck", str);
            }

            //清空plu
            @Override
            public void setClearPlu(String str) {
                WaitDialog.showWait(YangcanliActivity.this, "清空PLU，请稍后！");
                mCountDownTimer.start();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        BTSendDataUtils.sendData(mBluetoothDevice, 0xA6);
                        mDaoSession.deleteAll(SaveGoods.class);
                        saveGoodsList = mDaoSession.loadAll(SaveGoods.class);
                    }
                }).start();
            }

            //商品信息推送,批量下发商品
            @Override
            public void setGoodsBean(GoodsBean goodsBean) {
                if (goodsBean == null) {
                    return;
                }
                if (goodsBean.getData() == null) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mGoodsBean = goodsBean;
                        for (int i = 0; i < goodsBean.getData().size(); i++) {//所有商品数据保存到数据库
                            SaveGoods saveGoods = new SaveGoods();
                            saveGoods.setGoodsImg(goodsBean.getData().get(i).getGoodsImg());
                            saveGoods.setUnit(goodsBean.getData().get(i).getUnit());
                            saveGoods.setStallId(goodsBean.getData().get(i).getStallId());
                            saveGoods.setMaxGoodsPrice(goodsBean.getData().get(i).getMaxGoodsPrice());
                            saveGoods.setMerchantId(goodsBean.getData().get(i).getMerchantId());
                            saveGoods.setGoodsId(goodsBean.getData().get(i).getGoodsId());
                            saveGoods.setGoodsPrice(goodsBean.getData().get(i).getGoodsPrice());
                            saveGoods.setPlu(goodsBean.getData().get(i).getPlu());
                            saveGoods.setStallNo(goodsBean.getData().get(i).getStallNo());
                            saveGoods.setGoodsName(goodsBean.getData().get(i).getGoodsName());
                            saveGoods.setMarketId(goodsBean.getData().get(i).getMarketId());
                            saveGoods.setIsSendSuccess(0);
                            saveGoods.setIndexNo(goodsBean.getData().get(i).getIndexNo());
                            mDaoSession.insertOrReplace(saveGoods);
                        }
                        //查询savegoods表的所有数据
                        saveGoodsList = mDaoSession.loadAll(SaveGoods.class);

                        for (int i = 0; i < saveGoodsList.size(); i++) {
                            plu = saveGoodsList.get(i).getPlu();
                            BTSendDataUtils.sendPluData(mBluetoothDevice, saveGoodsList.get(i).getPlu(),
                                    Integer.parseInt(saveGoodsList.get(i).getGoodsPrice()),
                                    saveGoodsList.get(i).getGoodsName(), Integer.parseInt(saveGoodsList.get(i).getMaxGoodsPrice()),
                                    saveGoodsList.get(i).getIndexNo(), saveGoodsList.get(i).getUnit());
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        Message message = new Message();
                        message.what = 3;
                        mHandler.sendMessage(message);

                        saveGoodsList.get(0).setIsSendSuccess(1);
                        mDaoSession.update(saveGoodsList.get(0));
                    }
                }).start();
            }

            @Override
            public void setTransactionNum(String numOfTranaction) {
                transactionNumTv.setText(numOfTranaction);
                SPUtils.getInstance(getApplicationContext()).putSP("numOfTranaction", numOfTranaction);
            }

            @Override
            public void setUserInfo(LoginResponse loginResponse) {
                SPUtils.getInstance(getBaseContext()).putSP("businessLicensePic", loginResponse.getData().getBusinessLicensePic());
                SPUtils.getInstance(getBaseContext()).putSP("circulationLicense", loginResponse.getData().getCirculationLicense());
                initViewData(loginResponse);
                Message message = new Message();
                message.what = 12;
                mHandler.sendMessage(message);
            }

            @Override
            public void setMarketCheck(String str) {
                checkPcs.setText(str);
                SPUtils.getInstance(getBaseContext()).putSP("checkPcs", str);
            }

            @Override
            public void setCheckTime() {
            }

            @Override
            public void updateVersion(VersionApkBean versionApkBean) {
                Log.e(TAG, "updateVersion: " + versionApkBean.getCode() + versionApkBean.getData().getDownloadUrl() + "==" + versionApkBean.getData().getVersion());
                if (!PackageUtils.getLocalVersionName(getApplicationContext()).equals(versionApkBean.getData().getVersion())) {
                    WaitDialog.showWait(YangcanliActivity.this, "更新app中，请稍后..");
                    versionNew = versionApkBean.getData().getVersion();
                    downloadApk(versionApkBean.getData().getDownloadUrl());
                }
            }

            @Override
            public void setSysConfig(int sysNum, int sysValue) {
                BTSendDataUtils.sendSysConfig(mBluetoothDevice, sysNum, sysValue);
            }

            @Override
            public void getSysConfig(int indexNo) {
                mIndexNo = indexNo;
                BTSendDataUtils.getSysConfig(mBluetoothDevice, indexNo);
            }

            @Override
            public void changeUser(ChangeUser changeUser) {
                WaitDialog.showWait(YangcanliActivity.this, "清空PLU，请稍后！");
                changeUserTimer.start();
                //更改保存的用户登录信息
                SPUtils.getInstance(getApplicationContext()).putSP("stallNo", changeUser.getStallNo());
                SPUtils.getInstance(getApplicationContext()).putSP("marketId", changeUser.getMarketId() + "");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        BTSendDataUtils.sendData(mBluetoothDevice, 0xA6);
                        mDaoSession.deleteAll(SaveGoods.class);
                        saveGoodsList = mDaoSession.loadAll(SaveGoods.class);
                    }
                }).start();
            }
        });
    }

    private int mIndexNo;

    private void initGoodsPlay(List<SaveGoods> list, boolean status) {
        linkedHashMap = groupList(list);
        part1 = linkedHashMap.size();//商品信息的size
        if (!SPUtils.getInstance(getApplicationContext()).getSP("businessLicensePic").equals("")) {
            linkedHashMap.put(part1,
                    SPUtils.getInstance(getApplicationContext()).getSP("businessLicensePic"));
        } else {
            linkedHashMap.put(part1, null);
        }
        if (SPUtils.getInstance(getApplicationContext()).getSP("circulationLicense").equals("")) {
            linkedHashMap.put(part1 + 1, null);
        } else {
            linkedHashMap.put(part1 + 1,
                    SPUtils.getInstance(getApplicationContext()).getSP("circulationLicense"));
        }

        part2 = linkedHashMap.size();//完整map的size
        Log.e(TAG, "initData: " + part1 + "<====>" + part2);

        if (!status) {
            for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
                getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().getFragments().get(i)).commit();//清空播放内容
            }
        }
        if (linkedHashMap.size() >= 3) {
            MyBannerAdapter adapter = new MyBannerAdapter(getSupportFragmentManager(), linkedHashMap);
            mZBanner.setAdapter(adapter);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "initGoodsPlay: =============>" + adapter.getCount());
            mZBanner.star(3000, 500);
        } else {
            Toast.makeText(YangcanliActivity.this, "请补充商品和商户信息", Toast.LENGTH_SHORT).show();
            mZBanner.stop();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yangcanli);
        if (!BTManager.getInstance().isBluetoothOn()) {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    BTManager.getInstance().createConnection(SPUtils.getInstance(getApplicationContext()).getSP("device")).connect(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), new ConnectCallback() {
                        @Override
                        public void onSuccess() {
                            Log.e(TAG, "终于等到你: ");
                        }

                        @Override
                        public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                            Log.e(TAG, "onFail: " + errMsg + "没得到");
                        }
                    });
                    if (BTManager.getInstance().isBluetoothOn()) {
                        cancel();
                    }
                }
            }, 5000, 5000);
        }

        Gson gson = new Gson();
        LoginResponse loginResponse = gson.fromJson(SPUtils.getInstance(getApplicationContext()).getSP("loginResponse"), LoginResponse.class);
        Constants.sLoginResponse = loginResponse;
        Constants.STALL_ID = String.valueOf(loginResponse.getData().getStallId());
        //获取蓝牙设备的实例对象
        mBluetoothDevice = (BluetoothDevice) getIntent().getParcelableExtra("device");
        tanweihao = getIntent().getStringExtra("tanweihao");
        BaseApplication.sDevice = mBluetoothDevice;
        mGson = new Gson();
        mDaoSession = ((BaseApplication) getApplication()).getDaoSession();
        mZBanner = findViewById(R.id.zbanner);
        //查询sqlite如果有未下发的，就补发给称
        new Thread(new Runnable() {
            @Override
            public void run() {
                QueryBuilder<SaveGoods> saveGoodsQueryBuilder
                        = mDaoSession.queryBuilder(SaveGoods.class)
                        .where(SaveGoodsDao.Properties.IsSendSuccess.eq(0));
                List<SaveGoods> list = saveGoodsQueryBuilder.list();
                if (list != null) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            plu = list.get(i).getPlu();
                            BTSendDataUtils.sendPluData(mBluetoothDevice, list.get(i).getPlu(),
                                    Integer.parseInt(list.get(i).getGoodsPrice()),
                                    list.get(i).getGoodsName(), Integer.parseInt(list.get(i).getMaxGoodsPrice()),
                                    list.get(i).getIndexNo(), list.get(i).getUnit());
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            }
        }).start();


        backToServer = new BackToServer();

        setBroadCastReceiver();


        //开启service，通过servie开启websocket
        Intent intent = new Intent(YangcanliActivity.this, WebSocketService.class);
        intent.putExtra("stallId", SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
        intent.putExtra("marketId", SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
        startService(intent);

        initView();

        initListener();

        BTSendDataUtils.sendData(mBluetoothDevice, 0xC4);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mXBanner = findViewById(R.id.xbanner);
        mSmartTable = findViewById(R.id.smarttable);
        tableFl = findViewById(R.id.table_fl);
        tableMain = findViewById(R.id.table_main);

        sumTv = findViewById(R.id.sum_tv);
        sumTv1 = findViewById(R.id.sum_tv1);
        martetNameTv = findViewById(R.id.marketname_tv);

//        mBanner = findViewById(R.id.youthbanner);//
        mVideoView = findViewById(R.id.videoview);
        transactionNumTv = findViewById(R.id.transaction_num_tv);
        checkPcs = findViewById(R.id.check_pcs_tv);
        rateOfCheckTv = findViewById(R.id.rate_check_tv);
        mRecyclerView = findViewById(R.id.rv);
        touxiang = findViewById(R.id.touxiang);
        pingjia_img = findViewById(R.id.pingjia_img);
//        infoTv = findViewById(R.id.info_tv);
//        infoFl = findViewById(R.id.info_fl);
        bannerFl = findViewById(R.id.banner_fl);
        phonenumTv = findViewById(R.id.phonenum_tv);
        pingleiTv = findViewById(R.id.pinlei_tv);
        nameTv = findViewById(R.id.name_tv);
        tanweihaoTv = findViewById(R.id.tanweihao);
        alipayImg = findViewById(R.id.alipay_img);
        mRatingBar = findViewById(R.id.ratingbar);
        bannerFl.getBackground().setAlpha(50);
        if (!SPUtils.getInstance(getBaseContext()).getSP("todayCheapBean").isEmpty()) {
            TodayCheapBean todayCheapBean = mGson.fromJson(SPUtils.getInstance(getBaseContext()).getSP("todayCheapBean"), TodayCheapBean.class);
            if (todayCheapBean.getData() != null) {
                initTodayCheap(todayCheapBean);
            }
        }

        if (!SPUtils.getInstance(getBaseContext()).getSP("numOfTranaction").isEmpty()) {
            transactionNumTv.setText(SPUtils.getInstance(getBaseContext()).getSP("numOfTranaction"));
        }

        if (!SPUtils.getInstance(getBaseContext()).getSP("rateOfCheck").isEmpty()) {
            rateOfCheckTv.setText(SPUtils.getInstance(getBaseContext()).getSP("rateOfCheck"));
        }

        if (!SPUtils.getInstance(getBaseContext()).getSP("checkPcs").isEmpty()) {
            checkPcs.setText(SPUtils.getInstance(getBaseContext()).getSP("checkPcs"));
        }

//        mBanner.setPageTransformer(new DepthPageTransformer());
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
            }
        });


        list = new CopyOnWriteArrayList<>();

        tableRv = findViewById(R.id.table_rv);
        adapter = new TableAdapter(list, getApplicationContext());
        tableRv.setLayoutManager(mManager);
        tableRv.setAdapter(adapter);


        mSmartTable.getConfig().setShowYSequence(false);
        mSmartTable.getConfig().setShowXSequence(false);
        mSmartTable.getConfig().setShowTableTitle(false);
        TextBold fontStyle = new TextBold();
        fontStyle.setTextSize(28);

        mSmartTable.getConfig().setColumnTitleStyle(fontStyle);
        FontStyle fontStyle1 = new FontStyle();
        fontStyle1.setTextSize(28);
        mSmartTable.getConfig().setContentStyle(fontStyle1);
//        tableFl.setVisibility(View.VISIBLE);
        column1 = new Column<String>("商品名", "name");
        column2 = new Column<Double>("数量", "count");
        column3 = new Column<Double>("单价", "price");
        column4 = new Column<Double>("价格", "countPrice");
        column1.setMinWidth(370);
        column2.setMinWidth(370);
        column3.setMinWidth(370);
        column4.setMinWidth(370);

        /*
        初始化banner播放视频或图片
         */
        if (!TextUtils.isEmpty(SPUtils.getInstance(getBaseContext()).getSP("play_type"))) {
            switch (SPUtils.getInstance(getBaseContext()).getSP("play_type")) {
                case "1":
                    mVideoView.setVisibility(View.VISIBLE);
                    mXBanner.setVisibility(View.GONE);
                    mVideoView.setVideoPath(SPUtils.getInstance(getBaseContext()).getSP("video_url"));
                    mVideoView.start();
                    break;
                case "0":
                    mVideoView.setVisibility(View.GONE);
                    PlayBean playBean = mGson.fromJson(SPUtils.getInstance(getBaseContext()).getSP("img_url"), PlayBean.class);

                    mXBanner.setVisibility(View.VISIBLE);
                    mXBanner.loadImage(new XBanner.XBannerAdapter() {
                        @Override
                        public void loadBanner(XBanner xBanner, Object o, View view, int i) {
                            Glide.with(getApplicationContext())
                                    .load(playBean.getData().get(i).getAdvertisingSlogan())
                                    .into((ImageView) view);
                        }
                    });
                    mXBanner.setPageTransformer(Transformer.ZoomFade);
                    mXBanner.setAutoPalyTime(Integer.parseInt(playBean.getData().get(0).getInterval()) * 1000);
                    mXBanner.setBannerData(playBean.getData());
                    break;
            }
        }
    }

    /**
     * 初始化商户信息
     *
     * @param sLoginResponse
     */
    private void initViewData(LoginResponse sLoginResponse) {
        //星级评价
        if (sLoginResponse != null) {
            if (Constants.BASE_URL.equals("https://www.huilinshiji.com:8008")) {
                if (sLoginResponse.getData().getMerchantStar() >= 37) {
                    mRatingBar.setRating(5);
                } else if (sLoginResponse.getData().getMerchantStar() >= 33 && sLoginResponse.getData().getMerchantStar() <= 36) {
                    mRatingBar.setRating(4);
                } else if (sLoginResponse.getData().getMerchantStar() >= 29 && sLoginResponse.getData().getMerchantStar() <= 32) {
                    mRatingBar.setRating(3);
                } else if (sLoginResponse.getData().getMerchantStar() >= 25 && sLoginResponse.getData().getMerchantStar() <= 28) {
                    mRatingBar.setRating(2);
                } else if (sLoginResponse.getData().getMerchantStar() >= 21 && sLoginResponse.getData().getMerchantStar() <= 24) {
                    mRatingBar.setRating(1);
                } else {
                    mRatingBar.setRating(0);
                }
            } else {
                if (sLoginResponse.getData().getMerchantStar() >= 91) {
                    mRatingBar.setRating(5);
                } else if (sLoginResponse.getData().getMerchantStar() >= 81 && sLoginResponse.getData().getMerchantStar() <= 90) {
                    mRatingBar.setRating(4);
                } else if (sLoginResponse.getData().getMerchantStar() >= 71 && sLoginResponse.getData().getMerchantStar() <= 80) {
                    mRatingBar.setRating(3);
                } else if (sLoginResponse.getData().getMerchantStar() >= 61 && sLoginResponse.getData().getMerchantStar() <= 70) {
                    mRatingBar.setRating(2);
                } else if (sLoginResponse.getData().getMerchantStar() >= 51 && sLoginResponse.getData().getMerchantStar() <= 60) {
                    mRatingBar.setRating(1);
                } else {
                    mRatingBar.setRating(0);
                }
            }
        }
        //头像
        Picasso.with(this)
                .load(sLoginResponse.getData().getHeadThumb())
                .transform(new CircleTransForm())
                .into(touxiang);


        if (sLoginResponse != null) {
            //手机号
            phonenumTv.setText(sLoginResponse.getData().getPhone());
            //品类
            pingleiTv.setText(sLoginResponse.getData().getBusinessScope());
            //姓名
            nameTv.setText(sLoginResponse.getData().getMerchantName());
            //市场名称
            String marketName = sLoginResponse.getData().getMarketName();
            if (!TextUtils.isEmpty(marketName)) {
                String regex = "(.{1})";
                marketName = marketName.replaceAll(regex, "$1\t");
                marketName = marketName.substring(0, marketName.length() - 1);
                martetNameTv.setText(marketName);
            }

            //摊位号
            tanweihaoTv.setText(SPUtils.getInstance(getApplicationContext()).getSP("stallNo"));
            //评价二维码
            pingjia_img.setImageBitmap(QRCodeUtils.createQRCodeBitmap(
                    sLoginResponse.getData().getCodeRetrospective(),
                    800, 800, "utf-8", "H", "1",
                    Color.BLACK, Color.WHITE));

            //检测批次
            checkPcs.setText(sLoginResponse.getData().getMarketDetection() + "");
            //检测合格率
            rateOfCheckTv.setText(sLoginResponse.getData().getTestPassRate());
            //交易笔数
            transactionNumTv.setText(sLoginResponse.getData().getTransaction() + "");
        }

        //支付宝付款码
//        if (!NetUtils.ping()) {//如果ping不通
        if (!TextUtils.isEmpty(SPUtils.getInstance(getApplicationContext()).getSP("alipay"))) {
            Picasso.with(this)
                    .load(SPUtils.getInstance(getApplicationContext()).getSP("alipay"))
                    .into(alipayImg);
        }
//        } else {//ping通
//            Picasso.with(this)
//                    .load(sLoginResponse.getData().getAlipayPic())
//                    .into(alipayImg);
//        }
    }

    /**
     * 今日特价
     */
    private void initTodayCheap(TodayCheapBean todayCheapBean) {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);

//        mRecyclerView.setAdapter(new TodayCheapAdapter(todayCheapBean.getData(), getApplicationContext(), R.layout.item_tejia1));
        mRecyclerView.setAdapter(new AutoPollAdapterYCL(todayCheapBean.getData()));
        mRecyclerView.start(todayCheapBean.getData().size());
        String str = mGson.toJson(todayCheapBean);
        SPUtils.getInstance(getBaseContext()).putSP("todayCheapBean", str);
    }

    /**
     * 广告图片/视频播放
     * 初始化
     */
    private void initBanner(PlayBean playBean) {
        if (playBean == null) {
            return;
        }
        if (playBean.getData() == null) {
            return;
        }

        if ("视频".equals(playBean.getData().get(0).getShowType())) {
            mVideoView.setVisibility(View.VISIBLE);
            mXBanner.setVisibility(View.GONE);

            SPUtils.getInstance(getBaseContext()).putSP("play_type", "1");
            SPUtils.getInstance(getBaseContext()).putSP("video_url", playBean.getData().get(0).getAdvertisingSlogan());
            mVideoView.setVideoURI(Uri.parse(playBean.getData().get(0).getAdvertisingSlogan()));
            mVideoView.start();
        } else {
            mVideoView.setVisibility(View.GONE);
            mXBanner.setVisibility(View.VISIBLE);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SPUtils.getInstance(getBaseContext()).putSP("play_type", "0");
                    SPUtils.getInstance(getBaseContext()).putSP("img_url", mGson.toJson(playBean));
                }
            }).start();

            mXBanner.setVisibility(View.VISIBLE);
            mXBanner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner xBanner, Object o, View view, int i) {
                    Glide.with(getApplicationContext())
                            .load(playBean.getData().get(i).getAdvertisingSlogan())
                            .into((ImageView) view);
                }
            });
            mXBanner.setPageTransformer(Transformer.ZoomFade);
            mXBanner.setAutoPalyTime(Integer.parseInt(playBean.getData().get(0).getInterval()) * 1000);
            mXBanner.setBannerData(playBean.getData());
        }
    }

    @Override
    public void onBluetoothAdapterStateChanged(int state) {
        Log.e(TAG, "onBluetoothAdapterStateChanged: " + state);
    }

    private CountDownTimer changeUserTimer = new CountDownTimer(20 * 1000 + 50, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(getApplication().getPackageName());
            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(LaunchIntent);
        }
    };

    private CountDownTimer mCountDownTimer = new CountDownTimer(20 * 1000 + 50, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.e(TAG, "onTick: " + millisUntilFinished);
        }

        @Override
        public void onFinish() {
            WaitDialog.dismiss();
            Message message = new Message();
            message.what = 11;
            mHandler.sendMessage(message);
        }
    };
    private double byteTemp;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tableMain.setVisibility(View.VISIBLE);
                    sumTv1.setText("总金额：\u3000\u3000" + byteTemp + "元");
                    break;
                case 1:
                    adapter.setList(list);
                    tableRv.scrollToPosition(adapter.getItemCount() - 1);
//                    tableData = new TableData<Test>("", list, column1, column2, column3, column4);
//                    mSmartTable.setTableData(tableData);
                    break;
                case 2://蓝牙连接失败后
                    isBTConnect = false;
                    break;
                case 4:
                    tableMain.setVisibility(View.INVISIBLE);
                    break;
                case 3://批量下发
                case 10://单条下发
                case 11://清空plu
                case 12://下发商户信息
                    mZBanner.stop();
                    initGoodsPlay(saveGoodsList, false);
                    break;
            }
        }
    };

    /**
     * 如果{@link BTManager.Builder#setObserveAnnotationRequired(boolean)}设置为false时，无论加不加{@link Observe}注解都会收到消息。
     * 设置为true时，必须加{@link Observe}才会收到消息。
     * 默认为false，方法默认执行线程在{@link BTManager.Builder#setMethodDefaultThreadMode(ThreadMode)}指定
     */

    //FF 04 A2 59
    //读取到秤上报的数据
    @Observe
    @Override
    public void onRead(@NonNull BluetoothDevice device, @NonNull byte[] value) {
//        Log.e(TAG, "收到数据: " + DataConvertUtils.bytesToString(value));
        //遍历value，一个一个加进新的byte数组中，然后进行累加运算是否为0

        for (byte b : value) {
            mBytes = BTSendDataUtils.addBytesSingle(mBytes, b);

            //以0xFF开头的有效数据
            if (mBytes[0] == -1) {
                //数据长度达到4位开始判断命令类型
                if (mBytes.length >= 4) {
//                    Log.e(TAG, "收到数据: " + DataConvertUtils.bytesToString(mBytes));
                    //脏数据
                    if (mBytes[1] == 0 && mBytes[3] != -66 && mBytes[3] != -68 && mBytes[3] != -69 && mBytes[3] != -20) {
                        mBytes = new byte[]{};
                    }
                    //0xf0重连蓝牙时候出现的数据
                    if (mBytes[2] == -16 && mBytes.length == 6 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "0xf0重连蓝牙成功");
                        mBytes = new byte[]{};
                    }
                    //0xA2双向通信检测（握手）协议
                    else if (mBytes[2] == -94 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "双向通信检测（握手）协议: " + DataConvertUtils.bytesToString(mBytes));
                        BTSendDataUtils.sendData(mBluetoothDevice, 0xA3);
                        mBytes = new byte[]{};
                    }
                    //系统参数设置协议（秤返回）
                    else if (mBytes[2] == -54 && mBytes.length == 10 && BTSendDataUtils.getXor(mBytes) == 0) {
                        backToServer.setType(6);
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu("");
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("设置系统参数成功");
                        backToServer(backToServer, 6);
                        Log.e(TAG, "系统参数设置成功");
                        mBytes = new byte[]{};
                    }
                    //系统参数查询
                    else if (mBytes[2] == -55 && mBytes.length == 10 && BTSendDataUtils.getXor(mBytes) == 0) {
                        byte[] bytes = new byte[4];
                        System.arraycopy(mBytes, 5, bytes, 0, bytes.length);
                        UploadStatus uploadStatus = new UploadStatus();
                        uploadStatus.setIndexNo(mIndexNo);
                        uploadStatus.setIsLock(0);
                        uploadStatus.setMarketId(Integer.parseInt(SPUtils.getInstance(getApplicationContext()).getSP("marketId")));
                        uploadStatus.setStallId(Integer.parseInt(SPUtils.getInstance(getApplicationContext()).getSP("stallId")));
                        uploadStatus.setType(1);
                        uploadStatus.setValue(DataConvertUtils.bytesToIntNormal(bytes));
                        Model.parametersAndIsLock(uploadStatus);
                        Log.e(TAG, "系统参数查询");
                        mBytes = new byte[]{};
                    }
                    //查询抽检信息
                    else if (mBytes[2] == -61 && mBytes.length == 104 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "查询抽检信息");
                        mBytes = new byte[]{};
                    }
                    //文本参数下发协议
                    else if (mBytes[2] == -57 && mBytes.length == 5 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "文本参数下发协议");
                        mBytes = new byte[]{};
                    }
                    //下发批次协议
                    else if (mBytes[2] == -63 && mBytes.length == 16 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "下发批次协议");
                        mBytes = new byte[]{};
                    }
                    //0xA1电子秤开秤成功
                    else if (mBytes[2] == -95 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        backToServer.setType(3);
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu("");
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("开称成功！");
                        backToServer(backToServer, 3);
                        Log.e(TAG, "电子秤开秤");
                        mBytes = new byte[]{};
                    }
                    //0xA0电子秤锁秤成功
                    else if (mBytes[2] == -96 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        backToServer.setType(3);
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu("");
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("锁称成功！");
                        backToServer(backToServer, 3);
                        Log.e(TAG, "电子秤锁秤，不允许称重");
                        mBytes = new byte[]{};
                    }
                    //0xA7清空plu成功
                    else if (mBytes[2] == -89 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "清空plu成功");
                        mBytes = new byte[]{};
                    }
                    //0xA8会员卡查询
                    else if (mBytes[2] == -88 && mBytes.length == 36 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "会员卡查询");
                        mBytes = new byte[]{};
                    }
                    //0xAA会员退出登录
                    else if (mBytes[2] == -86 && mBytes.length == 36 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "会员退出登录");
                        mBytes = new byte[]{};
                    }
                    //0xAB扫描枪结果
                    else if (mBytes[2] == -85 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "扫描枪结果");
                        mBytes = new byte[]{};
                    }
                    //0xEF下发plu成功
                    else if (mBytes[2] == -17 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "0xEE下发plu成功：" + DataConvertUtils.bytesToString(mBytes));
                        backToServer.setType(1);//1:下发商品、2：小票信息、3：开秤锁称、4:下发校时
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu(plu);
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("下发plu成功！==" + plu);
                        backToServer(backToServer, 1);
                        mBytes = new byte[]{};
                    }
                    //0xC5下发时间成功
                    else if (mBytes[2] == -59 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        backToServer.setType(4);
                        backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                        backToServer.setPlu("");
                        backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                        backToServer.setStatusCode(200);
                        backToServer.setStatusMsg("下发时间成功");
                        backToServer(backToServer, 4);
                        mBytes = new byte[]{};
                    }
                    //0xBA取消交易累计
                    else if (mBytes[2] == -70 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "累清：" + DataConvertUtils.bytesToString(mBytes));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                tableFl.setVisibility(View.GONE);
                                tableMain.setVisibility(View.INVISIBLE);
                            }
                        });
                        mBytes = new byte[]{};
                    }
                    //0xD4累清协议
                    else if (mBytes[2] == -44 && mBytes.length == 4 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "累清：" + DataConvertUtils.bytesToString(mBytes));
                        mBytes = new byte[]{};
                    }
                    //0xA4菜品称重数量等上传
                    else if (mBytes[2] == -92 && mBytes.length == 39 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "菜品：" + DataConvertUtils.bytesToString(mBytes));
                        mBytes = new byte[]{};
                    }
                    //0xBC交易上传
                    else if (mBytes[3] == -68 && BTSendDataUtils.getXor(mBytes) == 0) {
                        byte[] lengthBytes = new byte[]{mBytes[1], mBytes[2]};
                        int length = DataConvertUtils.byteArrayToIntNormal(lengthBytes);
                        if (mBytes.length == length) {
                            byte[] byteOrderNo = new byte[12];
                            for (int i = 0; i < 12; i++) {
                                byteOrderNo[i] = mBytes[(41 + i) + mBytes[8] * 20];
                            }
                            byteOrderNo[0] = mBytes[41 + mBytes[8] * 20];//mBytes[61]  mBytes[81]...
                            Log.e(TAG, "交易上传：" + DataConvertUtils.bytesToString(mBytes));
                            BTSendDataUtils.sendUploadSuccess(mBluetoothDevice, byteOrderNo);
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = new Message();
                            message.what = 4;
                            mHandler.sendMessage(message);
                            SaveOrderBean saveOrderBean = new SaveOrderBean();
                            CopyOnWriteArrayList<SaveOrderBean.GoodsBean> list = new CopyOnWriteArrayList();
                            for (int j = 0; j < mBytes[8]; j++) {
                                byte[] byteIds = new byte[3];//商品ID
                                byteIds[0] = mBytes[20 * j + 9];
                                byteIds[1] = mBytes[20 * j + 9 + 1];
                                byteIds[2] = mBytes[20 * j + 9 + 2];
                                int goodsId = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteIds));
                                int marketId = Integer.parseInt(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                                int merchantId = Constants.sLoginResponse.getData().getId();
                                byte[] bytesPrice = new byte[3];//单价
                                bytesPrice[0] = mBytes[20 * j + 9 + 9];
                                bytesPrice[1] = mBytes[20 * j + 9 + 10];
                                bytesPrice[2] = mBytes[20 * j + 9 + 11];
                                int price = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(bytesPrice));
                                int stallId = Integer.parseInt(Constants.STALL_ID);
                                int unit = mBytes[20 * j + 28];

                                byte[] byteWeight = new byte[3];//每条重量
                                byteWeight[0] = mBytes[20 * j + 9 + 6];
                                byteWeight[1] = mBytes[20 * j + 9 + 7];
                                byteWeight[2] = mBytes[20 * j + 9 + 8];
                                int weight = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteWeight));
                                SaveOrderBean.GoodsBean goodsBean = new SaveOrderBean.GoodsBean();
                                goodsBean.setGoodsId(goodsId);
                                goodsBean.setMarketId(marketId);
                                goodsBean.setMerchantId(merchantId);
                                goodsBean.setPrice(price);
                                goodsBean.setStallId(stallId);
                                goodsBean.setUnit(unit);
                                goodsBean.setWeight(weight);
                                goodsBean.setGoodsName(goodsId);
                                goodsBean.setPlu(goodsId);
                                list.add(goodsBean);
                            }

                            saveOrderBean.setOrderNo(DataConvertUtils.bytesToString(byteOrderNo));
                            String paymentMethod = "";
                            switch (mBytes[4]) {
                                case 0:
                                    paymentMethod = "现金支付";
                                    break;
                                case -111:
                                    paymentMethod = "微信支付";
                                    break;
                                case -110:
                                    paymentMethod = "支付宝支付";
                                    break;
                                case -108:
                                    paymentMethod = "市民卡支付";
                                    break;
                                case -107:
                                    paymentMethod = "银联支付";
                                    break;
                                case -106:
                                    paymentMethod = "进货（仙游市场）";
                                    break;
                                case -105:
                                    paymentMethod = "电子会员卡";
                                    break;
                            }
                            saveOrderBean.setPaymentMethod(paymentMethod);
                            saveOrderBean.setGoods(list);
                            saveOrderBean.setIsReceipt("是");
                            saveOrderBean.setOriginalData(DataConvertUtils.bytesToString(mBytes));
                            if (NetUtils.ping()) {
                                addOrder(saveOrderBean, true);//保存订单
                                Log.e(TAG, "联网正常: ");
                            } else {
                                Log.e(TAG, "联网异常: " );
                                for (int i1 = 0; i1 < list.size(); i1++) {
                                    OffLineData offLineData = new OffLineData();
                                    offLineData.setGoodsId(saveOrderBean.getGoods().get(i1).getGoodsId());
                                    offLineData.setGoodsName(saveOrderBean.getGoods().get(i1).getGoodsName());
                                    offLineData.setMarketId(saveOrderBean.getGoods().get(i1).getMarketId());
                                    offLineData.setMerchantId(saveOrderBean.getGoods().get(i1).getMerchantId());
                                    offLineData.setPrice(saveOrderBean.getGoods().get(i1).getPrice());
                                    offLineData.setStallId(saveOrderBean.getGoods().get(i1).getStallId());
                                    offLineData.setUnit(saveOrderBean.getGoods().get(i1).getUnit());
                                    offLineData.setWeight(saveOrderBean.getGoods().get(i1).getWeight());
                                    offLineData.setPlu(saveOrderBean.getGoods().get(i1).getPlu());
                                    offLineData.setOrderNo(saveOrderBean.getOrderNo());
                                    offLineData.setPaymentMethod(saveOrderBean.getPaymentMethod());
                                    offLineData.setIsReceipt("离");
                                    mDaoSession.insert(offLineData);
                                }
                                Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
                            }
                            mBytes = new byte[]{};
                        }
                    }
                    //0xBE离线交易记录上传
                    else if (mBytes[3] == -66 && BTSendDataUtils.getXor(mBytes) == 0) {
                        byte[] lengthBytes = new byte[]{mBytes[1], mBytes[2]};
                        int length = DataConvertUtils.byteArrayToIntNormal(lengthBytes);
                        if (mBytes.length == length) {
                            Log.e(TAG, "离线上传：" + DataConvertUtils.bytesToString(mBytes));
                            SaveOrderBean saveOrderBean = new SaveOrderBean();
                            CopyOnWriteArrayList<SaveOrderBean.GoodsBean> list = new CopyOnWriteArrayList();
                            for (int j = 0; j < mBytes[8]; j++) {
                                byte[] byteIds = new byte[3];//商品ID
                                byteIds[0] = mBytes[20 * j + 9];
                                byteIds[1] = mBytes[20 * j + 9 + 1];
                                byteIds[2] = mBytes[20 * j + 9 + 2];
                                int goodsId = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteIds));
                                int marketId = Integer.parseInt(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                                int merchantId = Constants.sLoginResponse.getData().getId();
                                byte[] bytesPrice = new byte[3];//单价
                                bytesPrice[0] = mBytes[20 * j + 9 + 9];
                                bytesPrice[1] = mBytes[20 * j + 9 + 10];
                                bytesPrice[2] = mBytes[20 * j + 9 + 11];
                                int price = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(bytesPrice));
                                int stallId = Integer.parseInt(Constants.STALL_ID);
                                int unit = mBytes[20 * j + 28];

                                byte[] byteWeight = new byte[3];//每条重量
                                byteWeight[0] = mBytes[20 * j + 9 + 6];
                                byteWeight[1] = mBytes[20 * j + 9 + 7];
                                byteWeight[2] = mBytes[20 * j + 9 + 8];
                                int weight = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteWeight));
                                SaveOrderBean.GoodsBean goodsBean = new SaveOrderBean.GoodsBean();
                                goodsBean.setGoodsId(goodsId);
                                goodsBean.setMarketId(marketId);
                                goodsBean.setMerchantId(merchantId);
                                goodsBean.setPrice(price);
                                goodsBean.setStallId(stallId);
                                goodsBean.setUnit(unit);
                                goodsBean.setWeight(weight);
                                goodsBean.setGoodsName(goodsId);
                                goodsBean.setPlu(goodsId);
                                list.add(goodsBean);
                            }

                            byte[] byteOrderNo = new byte[12];
                            for (int i = 0; i < 12; i++) {
                                byteOrderNo[i] = mBytes[(41 + i) + mBytes[8] * 20];
                            }
                            byteOrderNo[0] = mBytes[41 + mBytes[8] * 20];//mBytes[61]  mBytes[81]...

                            saveOrderBean.setOrderNo(DataConvertUtils.bytesToString(byteOrderNo));
                            String paymentMethod = "";
                            switch (mBytes[4]) {
                                case 0:
                                    paymentMethod = "现金支付";
                                    break;
                                case -111:
                                    paymentMethod = "微信支付";
                                    break;
                                case -110:
                                    paymentMethod = "支付宝支付";
                                    break;
                                case -108:
                                    paymentMethod = "市民卡支付";
                                    break;
                                case -107:
                                    paymentMethod = "银联支付";
                                    break;
                                case -106:
                                    paymentMethod = "进货（仙游市场）";
                                    break;
                                case -105:
                                    paymentMethod = "电子会员卡";
                                    break;
                            }
                            saveOrderBean.setPaymentMethod(paymentMethod);
                            saveOrderBean.setGoods(list);
                            saveOrderBean.setIsReceipt("离");
                            saveOrderBean.setOriginalData(DataConvertUtils.bytesToString(mBytes));
                            if (NetUtils.ping()) {
                                addOrder(saveOrderBean, true);//保存订单
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(YangcanliActivity.this, "断网！！！！！！！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                for (int i1 = 0; i1 < list.size(); i1++) {
                                    OffLineData offLineData = new OffLineData();
                                    offLineData.setGoodsId(saveOrderBean.getGoods().get(i1).getGoodsId());
                                    offLineData.setGoodsName(saveOrderBean.getGoods().get(i1).getGoodsName());
                                    offLineData.setMarketId(saveOrderBean.getGoods().get(i1).getMarketId());
                                    offLineData.setMerchantId(saveOrderBean.getGoods().get(i1).getMerchantId());
                                    offLineData.setPrice(saveOrderBean.getGoods().get(i1).getPrice());
                                    offLineData.setStallId(saveOrderBean.getGoods().get(i1).getStallId());
                                    offLineData.setUnit(saveOrderBean.getGoods().get(i1).getUnit());
                                    offLineData.setWeight(saveOrderBean.getGoods().get(i1).getWeight());
                                    offLineData.setPlu(saveOrderBean.getGoods().get(i1).getPlu());
                                    offLineData.setOrderNo(saveOrderBean.getOrderNo());
                                    offLineData.setPaymentMethod(saveOrderBean.getPaymentMethod());
                                    offLineData.setIsReceipt(saveOrderBean.getIsReceipt());
                                    mDaoSession.insert(offLineData);
                                }
                            }

                            BTSendDataUtils.sendOffBleReply(mBluetoothDevice, byteOrderNo);
                            mBytes = new byte[]{};
                        }
                    }
                    //0xBB累计上报
                    else if (mBytes[3] == -69 && BTSendDataUtils.getXor(mBytes) == 0) {
                        Log.e(TAG, "尼玛：" + DataConvertUtils.bytesToString(mBytes));//数据杂乱了，因为没有阻塞发送的数据
                        byte[] lengthBytes = new byte[]{mBytes[1], mBytes[2]};//数据长度
                        int length = DataConvertUtils.byteArrayToIntNormal(lengthBytes);
                        if (mBytes.length == length) {
                            Log.e(TAG, "累计上传：" + DataConvertUtils.bytesToString(mBytes));
                            if (list != null) {
                                list.clear();
                            } else {
                                list = new CopyOnWriteArrayList<>();
                            }

//                            list = new CopyOnWriteArrayList<>();

                            byte[] byteSum = new byte[3];
                            byteSum[0] = mBytes[5];
                            byteSum[1] = mBytes[6];
                            byteSum[2] = mBytes[7];

                            if (mSmartTable != null) {
//                                            Log.e(TAG, "onRead: " + mBytes[8]);
                                for (int i1 = 0; i1 < mBytes[8]; i1++) {//看累计共几个商品 ,对数据集合进行操作
                                    byte[] bytes = new byte[3];//每条重量
                                    bytes[0] = mBytes[20 * i1 + 9 + 6];
                                    bytes[1] = mBytes[20 * i1 + 9 + 7];
                                    bytes[2] = mBytes[20 * i1 + 9 + 8];

                                    byte[] bytes1 = new byte[3];//单价
                                    bytes1[0] = mBytes[20 * i1 + 9 + 9];
                                    bytes1[1] = mBytes[20 * i1 + 9 + 10];
                                    bytes1[2] = mBytes[20 * i1 + 9 + 11];

                                    byte[] bytes2 = new byte[3];//总金额
                                    bytes2[0] = mBytes[20 * i1 + 9 + 12];
                                    bytes2[1] = mBytes[20 * i1 + 9 + 13];
                                    bytes2[2] = mBytes[20 * i1 + 9 + 14];

                                    //单位
                                    byte unit = mBytes[20 * i1 + 8 + 20];
//                                    Log.e(TAG, "单位: " + unit);

                                    byte[] bytesId = new byte[3];//商品ID
                                    bytesId[0] = mBytes[20 * i1 + 9];
                                    bytesId[1] = mBytes[20 * i1 + 9 + 1];
                                    bytesId[2] = mBytes[20 * i1 + 9 + 2];
                                    String strName = "临时称重";
                                    List<SaveGoods> saveGoods = mDaoSession.loadAll(SaveGoods.class);

                                    for (SaveGoods saveGoods1 : saveGoods) {
                                        if (String.valueOf(DataConvertUtils.byteArrayToIntNormal1(bytesId)).equals(saveGoods1.getPlu())) {
                                            strName = saveGoods1.getGoodsName();
                                        }
                                    }

                                    String unitType = "";
                                    switch (unit) {
                                        case 1:
                                        case 2:
                                        case 20:
                                        case 21:
                                        case 22:
                                        case 23:
                                        case 24:
                                        case 25:
                                        case 26:
                                        case 27:
                                        case 28:
                                        case 29:
                                        case 30:
                                        case 31:
                                        case 32:
                                            unitType = "计件";
                                            break;
                                        case 3:
                                        case 4:
                                        case 5:
                                        case 6:
                                        case 7:
                                        case 8:
                                            unitType = "计重";
                                            break;
                                    }
                                    double count = 0;
                                    double price = 0;
                                    switch (unitType) {
                                        case "计件":
                                            count = DataConvertUtils.bytesToIntNormal(bytes);//单位是件数
                                            price = DataConvertUtils.bytesToInt_100(bytes1);//元/件
                                            break;
                                        case "计重":
                                            count = DataConvertUtils.bytesToInt(bytes) * 2;//公斤转斤
                                            price = DataConvertUtils.bytesToInt_100(bytes1) / 2.0;//元/公斤===>元/斤
                                            break;
                                    }
                                    double countPrice = DataConvertUtils.bytesToInt_100(bytes2);
                                    list.add(new Test(strName, count, price, countPrice));
                                }
                            }

                            Message message1 = new Message();
                            message1.what = 1;
                            mHandler.sendMessage(message1);

                            byteTemp = DataConvertUtils.bytesToInt_100(byteSum);
                            Message message = new Message();
                            message.what = 0;
                            mHandler.sendMessage(message);
                            mBytes = new byte[]{};
                        }
                    }
                    //0xEC异常交易记录上传
                    else if (mBytes[3] == -20 && BTSendDataUtils.getXor(mBytes) == 0) {
                        byte[] lengthBytes = new byte[]{mBytes[1], mBytes[2]};
                        int length = DataConvertUtils.byteArrayToIntNormal(lengthBytes);
                        Log.e(TAG, "onRead: =============>" + length + "真实数据：" + DataConvertUtils.bytesToString(mBytes));
                        if (mBytes.length == length) {
                            Log.e(TAG, "异常数据：" + DataConvertUtils.bytesToString(mBytes));
                            byte[] byteOrderNo = new byte[12];
                            for (int i = 0; i < 12; i++) {
                                byteOrderNo[i] = mBytes[(41 + i) + mBytes[8] * 20];
                            }
                            byteOrderNo[0] = mBytes[41 + mBytes[8] * 20];//mBytes[61]  mBytes[81]...
                            BTSendDataUtils.sendUploadErrorSuccess(mBluetoothDevice, byteOrderNo);

                            SaveOrderBean saveOrderBean = new SaveOrderBean();
                            CopyOnWriteArrayList<SaveOrderBean.GoodsBean> list = new CopyOnWriteArrayList();
                            for (int j = 0; j < mBytes[8]; j++) {
                                byte[] byteIds = new byte[3];//商品ID
                                byteIds[0] = mBytes[20 * j + 9];
                                byteIds[1] = mBytes[20 * j + 9 + 1];
                                byteIds[2] = mBytes[20 * j + 9 + 2];
                                int goodsId = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteIds));
                                int marketId = Integer.parseInt(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                                int merchantId = Constants.sLoginResponse.getData().getId();
                                byte[] bytesPrice = new byte[3];//单价
                                bytesPrice[0] = mBytes[20 * j + 9 + 9];
                                bytesPrice[1] = mBytes[20 * j + 9 + 10];
                                bytesPrice[2] = mBytes[20 * j + 9 + 11];
                                int price = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(bytesPrice));
                                int stallId = Integer.parseInt(Constants.STALL_ID);
                                int unit = mBytes[20 * j + 28];

                                byte[] byteWeight = new byte[3];//每条重量
                                byteWeight[0] = mBytes[20 * j + 9 + 6];
                                byteWeight[1] = mBytes[20 * j + 9 + 7];
                                byteWeight[2] = mBytes[20 * j + 9 + 8];
                                int weight = DataConvertUtils.hexToInt(DataConvertUtils.bytesToString(byteWeight));
                                SaveOrderBean.GoodsBean goodsBean = new SaveOrderBean.GoodsBean();
                                goodsBean.setGoodsId(goodsId);
                                goodsBean.setMarketId(marketId);
                                goodsBean.setMerchantId(merchantId);
                                goodsBean.setPrice(price);
                                goodsBean.setStallId(stallId);
                                goodsBean.setUnit(unit);
                                goodsBean.setWeight(weight);
                                goodsBean.setGoodsName(goodsId);
                                goodsBean.setPlu(goodsId);
                                list.add(goodsBean);
                            }

                            saveOrderBean.setOrderNo(DataConvertUtils.bytesToString(byteOrderNo));
                            String paymentMethod = "";
                            switch (mBytes[4]) {
                                case 0:
                                    paymentMethod = "现金支付";
                                    break;
                                case -111:
                                    paymentMethod = "微信支付";
                                    break;
                                case -110:
                                    paymentMethod = "支付宝支付";
                                    break;
                                case -108:
                                    paymentMethod = "市民卡支付";
                                    break;
                                case -107:
                                    paymentMethod = "银联支付";
                                    break;
                                case -106:
                                    paymentMethod = "进货（仙游市场）";
                                    break;
                                case -105:
                                    paymentMethod = "电子会员卡";
                                    break;
                            }
                            saveOrderBean.setPaymentMethod(paymentMethod);
                            saveOrderBean.setGoods(list);
                            saveOrderBean.setIsReceipt("否");
                            saveOrderBean.setOriginalData(DataConvertUtils.bytesToString(mBytes));
                            if (NetUtils.ping()) {
                                addOrder(saveOrderBean, true);//保存订单
                            } else {
                                for (int i1 = 0; i1 < list.size(); i1++) {
                                    OffLineData offLineData = new OffLineData();
                                    offLineData.setGoodsId(saveOrderBean.getGoods().get(i1).getGoodsId());
                                    offLineData.setGoodsName(saveOrderBean.getGoods().get(i1).getGoodsName());
                                    offLineData.setMarketId(saveOrderBean.getGoods().get(i1).getMarketId());
                                    offLineData.setMerchantId(saveOrderBean.getGoods().get(i1).getMerchantId());
                                    offLineData.setPrice(saveOrderBean.getGoods().get(i1).getPrice());
                                    offLineData.setStallId(saveOrderBean.getGoods().get(i1).getStallId());
                                    offLineData.setUnit(saveOrderBean.getGoods().get(i1).getUnit());
                                    offLineData.setWeight(saveOrderBean.getGoods().get(i1).getWeight());
                                    offLineData.setPlu(saveOrderBean.getGoods().get(i1).getPlu());
                                    offLineData.setOrderNo(saveOrderBean.getOrderNo());
                                    offLineData.setPaymentMethod(saveOrderBean.getPaymentMethod());
                                    offLineData.setIsReceipt(saveOrderBean.getIsReceipt());
                                    mDaoSession.insert(offLineData);
                                }
                            }
                            mBytes = new byte[]{};
                        }
                    }
//                    else {
//                        Log.e(TAG, "其他数据：" + DataConvertUtils.bytesToString(mBytes));
//                    }
                }
            } else {
                mBytes = new byte[]{};
            }
        }
    }

    @Override
    public void onWrite(@NonNull BluetoothDevice device, @NonNull String tag, @NonNull byte[] value, boolean result) {
        Log.e(TAG, "onWrite: " + result + "==>>" + tag + "==>>" + DataConvertUtils.bytesToString(value));
    }

    private boolean isBTConnect = true;

    /**
     * 使用{@link Observe}确定要接收消息，{@link RunOn}指定在主线程执行方法，设置{@link Tag}防混淆后找不到方法
     */
    @Tag("onConnectionStateChanged")
    @Observe
    @RunOn(ThreadMode.BACKGROUND)
    @Override
    public void onConnectionStateChanged(@NonNull BluetoothDevice device, int state) {
        Log.e(TAG, "到底是什么情况: " + state);
        //主线程中
        //对照connection里的状态值
        if (state == 0 || state == 1) {
            Log.e(TAG, "正在想办法: ");
            isBTConnect = false;
//            WaitDialog.showWait(YangcanliActivity.this, "蓝牙重连中...");
            BTManager.getInstance().createConnection(SPUtils.getInstance(getApplicationContext()).getSP("device"))
                    .connect(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), new ConnectCallback() {
                        @Override
                        public void onSuccess() {
                            isBTConnect = true;
                            Log.e(TAG, "重连成功！" + Thread.currentThread().getName());
                            mBluetoothDevice = device;
                            //根据未发送成功的商品
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    QueryBuilder<SaveGoods> saveGoodsQueryBuilder = mDaoSession.queryBuilder(SaveGoods.class)
                                            .where(SaveGoodsDao.Properties.IsSendSuccess.eq(0)).orderAsc(SaveGoodsDao.Properties.Plu);
                                    List<SaveGoods> list = saveGoodsQueryBuilder.list();
                                    for (int i = 0; i < list.size(); i++) {
                                        BTSendDataUtils.sendPluData(mBluetoothDevice, list.get(i).getPlu(),
                                                Integer.parseInt(list.get(i).getGoodsPrice()),
                                                list.get(i).getGoodsName(), Integer.parseInt(list.get(i).getMaxGoodsPrice()), list.get(i).getIndexNo(), list.get(i).getUnit());
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                            }).start();

//                    WaitDialog.dismiss();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "重连成功！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                            isBTConnect = false;
                            Log.e(TAG, "重连失败了: " + errMsg);
                        }
                    });
        }
    }

    @Override
    public void onChanged(Object o) {
        Log.e(TAG, "onChanged: ");
    }

    private NetWorkStateReceiver mNetWorkStateReceiver;

    /**
     * 接收数据的广播监听
     * websocket
     */
    private void setBroadCastReceiver() {
        mWSDataReceiver = new WSDataReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        registerReceiver(mWSDataReceiver, filter);

        if (mNetWorkStateReceiver == null) {
            mNetWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter netIntentFilter = new IntentFilter();
        netIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetWorkStateReceiver, netIntentFilter);
    }

    private class MyBannerAdapter extends ZBannerAdapter {
        private LinkedHashMap mLinkedHashMap;

        public MyBannerAdapter(FragmentManager fm, LinkedHashMap list) {
            super(fm);
            mLinkedHashMap = list;
        }

        @Override
        public Fragment getItem(int position) {
            if (position < part1) {
                return BannerFragmentRv.newInstance(position, (List<SaveGoods>) mLinkedHashMap.get(position));
            }
            return BannerFragment.newInstance(position, (String) mLinkedHashMap.get(position));
        }

        @Override
        public int getCount() {
            return mLinkedHashMap == null ? 0 : mLinkedHashMap.size();
        }
    }

    /**
     * imageview
     */
    public static class BannerFragment extends Fragment {
        private static final String POSITION = "position";

        public static BannerFragment newInstance(int position, String strings) {
            BannerFragment fragment = new BannerFragment();
            Bundle args = new Bundle();
            args.putString("imgurl", strings);
            args.putInt(POSITION, position);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            //imageview
            View view = inflater.inflate(R.layout.img, container, false);
            ImageView img = view.findViewById(R.id.img);
            Glide.with(getContext())
                    .load(getArguments().getString("imgurl"))
                    .fallback(R.drawable.touming)
                    .into(img);
//            img.setScaleType(ImageView.ScaleType.);

            return view;
        }
    }

    /**
     * RV
     */
    public static class BannerFragmentRv extends Fragment {
        private static final String POSITION = "position";

        //保存所有数据的状态避免其他生命周期导致数据消失
        public static BannerFragmentRv newInstance(int position, List<SaveGoods> list) {
            ArrayList list1 = new ArrayList();
            list1.addAll(list);
            Log.e(TAG, "newInstance: " + list1.size());
            BannerFragmentRv fragment = new BannerFragmentRv();
            Bundle args = new Bundle();
            args.putCharSequenceArrayList("rv", list1);
            args.putInt(POSITION, position);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            Log.e(TAG, "onCreateView: ");
            ArrayList list = getArguments().getCharSequenceArrayList("rv");
            ArrayList<SaveGoods> list1 = new ArrayList<>();
            list1.addAll(list);
            //recyclerview
            View viewRv = inflater.inflate(R.layout.recyclerview1, container, false);
            RecyclerView recyclerView = viewRv.findViewById(R.id.recyclerview1);
            GridLayoutManager manager = new GridLayoutManager(getContext(), 5);
            GoodsAdapter adapter = new GoodsAdapter(getContext(), R.layout.item_goods);
            adapter.setGoodsBeans(list1);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
            return viewRv;
        }
    }

    /**
     * 实现java 中 list集合中有几十万条数据,每100条为一组取出
     *
     * @param list 可穿入几十万条数据的List
     * @return map 每一Kye中有100条数据的List
     */
    private LinkedHashMap groupList(List<SaveGoods> list) {
        int listSize = list.size();
        int toIndex = 10;
        LinkedHashMap map = new LinkedHashMap();     //用map存起来新的分组后数据
        int keyToken = 0;
        for (int i = 0; i < list.size(); i += 10) {
            if (i + 10 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                toIndex = listSize - i;
            }
            List newList = list.subList(i, i + toIndex);
            map.put(keyToken, newList);
            keyToken++;
        }

        return map;
    }

    /**
     * 交易数据上报
     *
     * @param saveOrderBean
     * @param isPrint       是否打印
     */
    private void addOrder(SaveOrderBean saveOrderBean, boolean isPrint) {
        ApiWrapper.getInstance().addOrder(saveOrderBean)
                .compose(RxHelper.to_mian())
                .subscribe(new MyObserver<OrderResult>() {
                    @Override
                    public void onError(ExceptionHandle.ResponseException responseException) {
                        Log.e(TAG, "onError: " + responseException.getMessage());
                    }

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull OrderResult orderResult) {
//                        if (isPrint) {
                        tableMain.setVisibility(View.INVISIBLE);
//                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 上传离线交易数据到服务器
     *
     * @param offLineList
     */
    private void uploadOffLineData(List<OffLineData> offLineList) {
        ApiWrapper.getInstance().addOffLineOrder(offLineList)
                .compose(RxHelper.to_mian())
                .subscribe(new MyObserver<NormalResponse>() {
                    @Override
                    public void onError(ExceptionHandle.ResponseException responseException) {

                    }

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull NormalResponse normalResponse) {
                        mDaoSession.deleteAll(OffLineData.class);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 秤响应的接口(调用)
     * 1:下发商品、2：小票信息、3：开秤锁称、4:下发校时
     *
     * @param data
     */
    private void backToServer(BackToServer data, int type) {
        ApiWrapper.getInstance().backToServer(data)
                .compose(RxHelper.to_mian())
                .subscribe(new MyObserver<NormalResponse>() {
                    @Override
                    public void onError(ExceptionHandle.ResponseException responseException) {
                    }

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull NormalResponse s) {
                        if (s.getCode() == 200) {
                            switch (type) {
                                case 1:
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //先查询plu相等的数据
                                            QueryBuilder<SaveGoods> saveGoodsQueryBuilder
                                                    = mDaoSession.queryBuilder(SaveGoods.class)
                                                    .where(SaveGoodsDao.Properties.Plu.eq(plu));
                                            //因为只有一条，所以取第1位
                                            List<SaveGoods> list = saveGoodsQueryBuilder.list();
                                            Log.e(TAG, "run: " + list.size());
                                            if (list.size() > 0) {
                                                list.get(0).setIsSendSuccess(1);
                                                //更新这条数据为已下发
                                                mDaoSession.update(list.get(0));
                                            }
                                        }
                                    }).start();
                                    break;
                            }
                        }

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private String versionNew;

    private void downloadApk(String downloadUrl) {
        try {
            DownloadUtils.downloadFile(YangcanliActivity.this, Environment.getExternalStorageDirectory().getAbsolutePath(),
                    "/yangcanli.apk", downloadUrl, new DownloadUtils.DownLoadListener() {
                        @Override
                        public void onDownloading(int progress) {
                            Log.e(TAG, "onDownloading: " + progress);
                        }

                        @Override
                        public void onDownloadSuccess() {
                            Log.e(TAG, "onDownloadSuccess: ");
                            SlientInstall.install(Environment.getExternalStorageDirectory().getAbsolutePath() + "/yangcanli.apk");
                        }

                        @Override
                        public void onDownloadFailed() {
                            WaitDialog.dismiss();
                            BTManager.getInstance().startDiscovery();
                            Log.e(TAG, "onDownloadFailed: ");
                            BackToServer backToServer = new BackToServer();
                            backToServer.setType(5);//1:下发商品、2：小票信息、3：开秤锁称、4:下发校时5:下发更新apk
                            backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                            backToServer.setPlu("");
                            backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                            backToServer.setStatusCode(200);
                            backToServer.setStatusMsg(versionNew);
                            ApiWrapper.getInstance().backToServer(backToServer)
                                    .compose(RxHelper.to_mian())
                                    .subscribe(new MyObserver<NormalResponse>() {
                                        @Override
                                        public void onError(ExceptionHandle.ResponseException responseException) {

                                        }

                                        @Override
                                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                                        }

                                        @Override
                                        public void onNext(@io.reactivex.annotations.NonNull NormalResponse normalResponse) {

                                        }

                                        @Override
                                        public void onComplete() {

                                        }
                                    });

                        }
                    });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


}

